import wsgiref.handlers
from google.appengine.ext import webapp 
from google.appengine.api import datastore_types
from google.appengine.api import urlfetch
from google.appengine.api import images
import StringIO
import struct

from pyth.inventionmodels import *

#base = "http://www1.cs.columbia.edu/~ollie/CraftComputing/"

import StringIO
import struct

def getImageInfo(data):
    data = str(data)
    size = len(data)
    height = -1
    width = -1
    content_type = ''

    # handle GIFs
    if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
        # Check to see if content_type is correct
        content_type = 'image/gif'
        w, h = struct.unpack("<HH", data[6:10])
        width = int(w)
        height = int(h)

    # See PNG 2. Edition spec (http://www.w3.org/TR/PNG/)
    # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR'
    # and finally the 4-byte width, height
    elif ((size >= 24) and data.startswith('\211PNG\r\n\032\n')
          and (data[12:16] == 'IHDR')):
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[16:24])
        width = int(w)
        height = int(h)

    # Maybe this is for an older PNG version.
    elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'):
        # Check to see if we have the right content type
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[8:16])
        width = int(w)
        height = int(h)

    # handle JPEGs
    elif (size >= 2) and data.startswith('\377\330'):
        content_type = 'image/jpeg'
        jpeg = StringIO.StringIO(data)
        jpeg.read(2)
        b = jpeg.read(1)
        try:
            while (b and ord(b) != 0xDA):
                while (ord(b) != 0xFF): b = jpeg.read(1)
                while (ord(b) == 0xFF): b = jpeg.read(1)
                if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
                    jpeg.read(3)
                    h, w = struct.unpack(">HH", jpeg.read(4))
                    break
                else:
                    jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
                b = jpeg.read(1)
            width = int(w)
            height = int(h)
        except struct.error:
            pass
        except ValueError:
            pass

    return content_type, width, height


class GetText(webapp.RequestHandler):
  def get(self):
    path = self.request.get('path')
    image = Image.gql("WHERE path = :1", path)
    if (image.count() > 0 and image[0].im != None):
        self.response.out.write(image[0].im)
    else:
        self.response.out.write("Couldn't load textfile")

class GetImage(webapp.RequestHandler):
  def get(self):
    path = self.request.get('path')
    image = Image.gql("WHERE path = :1", path)
    if (image.count() > 0 and image[0].im != None):
        self.response.headers['Content-Type'] = 'image/jpg'
        self.response.out.write(image[0].im)
    else:
        #image = Image.gql("WHERE path = :1", "/mainimages/01_11a.jpg")
        image = Image.gql("WHERE path = :1", "/albumimages/01_11a/01.jpg")
        if (image.count() > 0 and image[0].im != None):
            self.response.headers['Content-Type'] = 'image/jpg'
            self.response.out.write(image[0].im)
        else:
            self.response.out.write("Couldn't load default image")

class GetMediumImage(webapp.RequestHandler):
  def get(self):
    path = self.request.get('path')
    image = Image.gql("WHERE path = :1", path)
    if (image.count() > 0 and image[0].im != None):
        type, w, h = getImageInfo(image[0].im)
        asp = float(w)/h; nw = 320; nh = 240
        if asp > 4./3:
            nh = int(240./asp);
        else:
            nw = int(320*asp) 
        self.response.headers['Content-Type'] = 'image/jpg'
        self.response.out.write(images.resize(image[0].im, nw, nh))
    else:
        image = Image.gql("WHERE path = :1", "/mainimages/01_11a.jpg")
        if (image.count() > 0 and image[0].im != None):
            type, w, h = getImageInfo(image[0].im)
            asp = float(w)/h; nw = 320; nh = 240
            if asp > 4./3:
                nh = int(240./asp);
            else:
                nw = int(320*asp) 
            self.response.headers['Content-Type'] = 'image/jpg'
            self.response.out.write(images.resize(image[0].im, nw, nh))
        else:
            self.response.out.write("Couldn't load default image")

class GetThumbImage(webapp.RequestHandler):
  def get(self):
    path = self.request.get('path')
    image = Image.gql("WHERE path = :1", path)
    if (image.count() > 0 and image[0].im != None):
        self.response.headers['Content-Type'] = 'image/jpg'
        type, w, h = getImageInfo(image[0].im)
        asp = float(w)/h; nw = 60; nh = 60
        im = images.Image(image[0].im)
        if asp > 1.:
            im.resize(int(nw*asp), nh)
            im.crop((w/2.-h/2. + 1)/w, 0., (w/2.+h/2. - 1)/w, 1.)
            #im.crop(.5-1./asp/2., 0., .5+1./asp/2., 1.)
        else:
            im.resize(nw, int(nh/asp))
            im.crop((h/2.-w/2. +1)/h, 0., (h/2.+w/2. - 1)/h, 1.)
            #im.crop(0., .5-asp/2., 1., .5+asp/2.)
        self.response.out.write(im.execute_transforms())
    else:
        image = Image.gql("WHERE path = :1", "/mainimages/01_11a.jpg")
        if (image.count() > 0 and image[0].im != None):
            self.response.headers['Content-Type'] = 'image/jpg'
            type, w, h = getImageInfo(image[0].im)
            asp = float(w)/h; nw = 60; nh = 60
            im = images.Image(image[0].im)
            if asp > 1.:
                im.resize(int(nw*asp), nh)
                im.crop(.5-1./asp/2., 0., .5+1./asp/2., 1.)
            else:
                im.resize(nw, int(nh/asp))
            self.response.out.write(im.execute_transforms())
        else:
            self.response.out.write("Couldn't load default image")

def main():
  application = webapp.WSGIApplication(
                                       [('/image/reg', GetImage),
                                        ('/image/text', GetText),
                                        ('/image/med', GetMediumImage),
                                        ('/image/thumb', GetThumbImage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)